package com.jn.glide.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.glide.R;
import com.jn.glide.entity.MovieEntity;

import java.util.List;

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
    private List<MovieEntity.DataDTO> mList;
    private Context mContext;
    private OnItemClickListener mListener;

    public MovieAdapter(List<MovieEntity.DataDTO> list, Context context) {
        mList = list;
        mContext = context;
    }

    public void updateData(List<MovieEntity.DataDTO> list) {
        mList.clear();
        mList = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MovieEntity.DataDTO movie = mList.get(position);
        holder.textView1.setText(movie.getTitle());
        holder.textView2.setText(movie.getDesc());
        Glide.with(mContext).load(movie.getPic()).into(holder.imageView);
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onItemClick(movie.getPic());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView1;
        TextView textView2;
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView1 = itemView.findViewById(R.id.movie_name);
            textView2 = itemView.findViewById(R.id.movie_desc);
            imageView = itemView.findViewById(R.id.movie_pic);
        }
    }

    public void addItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(String url);
    }
}
